﻿/***********************/
/* (c) Alexandru Lungu */
/*  Challenge is Life! */
/* www.challenge-me.ws */
/***********************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using System.Threading;

namespace Coowork.WcfServer
{
    public class ChallengePrincipal: IPrincipal
    {
        IIdentity identity;
        string[] roles = null;

        public ChallengePrincipal(IIdentity identity)
        {
            this.identity = identity;
        }

        public static ChallengePrincipal Current
        {
            get
            {
                return Thread.CurrentPrincipal as ChallengePrincipal;
            }
        }

        public IIdentity Identity
        {
            get { return identity; }
        }

        public string[] Roles
        {
            get
            {
                EnsureRoles();
                return roles;
            }
        }

        public bool IsInRole(string role)
        {
            EnsureRoles();
            return roles != null ? roles.Contains(role) : false;
        }

        protected virtual void EnsureRoles()
        {
            // get the roles for the identity from a database (or other source)
            // and cache them for subsequent requests

            // here we'll add a few roles as example
            if (identity.Name == "Allex")
                roles = new string[] { "User", "Admin", "Manager" };
        }
    }
}
